<?php
namespace app\common\lib\file_operate;
use app\common\lib\Upload;

/**
 *文件操作类
 */
class FileOperate
{
    //上传规则
    protected $rule =[
        'size' => 10485760, //字节 1MB = 1048576B
        'ext'  => ['gif', 'jpeg', 'png', 'bmp', 'jpg', 'tiff'], //检查后缀
        'type' => ['image/gif', 'image/jpeg', 'image/png', 'image/bmp', 'image/jpg', 'image/tiff'], //图片类型
    ];

    /**
     * 上传图片
     * @param info 文件信息
     * @param path 保存路径
     * @param rule 规则
     */
    public function uploadImg(&$info = [], $path = '/upload', &$rule = [])
    {
        $filename = $info['tmp_name'];

        $upload = new Upload($filename, 'rb');

        $upload->setUploadInfo($info);

        if (empty($rule)) {
            $rule = $this->rule;
        }

        //验证规则
        $upload->validate($rule);
        //移动文件
        $move = $upload->move('.' . $path);

        if (false == $move) {

            $error = $upload->getError();

            return ['status' => false, 'message' => $error, 'code' => 101];

        } else {

            $name = $move->getSaveName();

            $path = $path . '/' . $name;
            //返回上传地址
            return ['status' => true, 'message' => '上传成功', 'code' => 200, 'data' => $path];
        }
    }

    /**
     * 写入config文件
     * $directory   strint  common 目录下
     * $fileName    string  文件名
     * $data        array   写入数据
     * @return [type] [description]
     */
    public function writeConfigFile($directory = "config", $fileName = "", $data = "")
    {
        if (is_array($data) || is_object($data)) {

            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }

        if (!is_string($data)) {

            return false;
        }

        $path = ROOT_PATH . '/app/common/';

        if (!file_exists($path)) {
            //目录不存在
            return false;
        }

        $path .= '/' . $directory;

        if (!file_exists($path)) {

            try {

                mkdir($path, 0777, true);

            } catch (\Exception $e) {

                return false;
            }
        }

        $res = chmod($path, 0777);

        $access = fileperms($path);

        $path .= "/" . $fileName;

        try {
            //lock file and save data
            file_put_contents($path, $data, LOCK_EX);
            //fopen($path,'w');
        } catch (\Exception $e) {

            return false;
        }
        return true;
    }

    /**
     * 读取文件
     * @param  $directory 目录名
     * @param  $fileName 要读的文件名
     * @return [type]            [description]
     */
    public function readConfigFile($directory = "config", $fileName = "")
    {

        $path = ROOT_PATH . '/app/common/' . $directory . '/' . $fileName;

        if (file_exists($path)) {

            $exts = explode('.', $fileName);

            $end = end($exts);

            if ($end == 'php') {

                $data = require $path;

            } else {

                $data = file_get_contents($path);
            }

            return $data;

        } else {

            return "";
        }
    }

    /**
     * 远程下载
     * @param  $url 请求连接
     * @param  $path 本地地址 例 C:/path
     */
    public function fileDownload($url = '', $path = '')
    {
        $res = ['status' => 'success', 'message' => '下载完成'];

        $arr = parse_url($url);

        $fileName = basename($arr['path']);

        if (empty($fileName)) {
            return ['status' => 'error', 'message' => $url . '不是一个文件！', 'code' => '102'];
        }

        header("Content-type: text/html; charset=utf-8");

        try {

            $arrContextOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                ]
            ];

            $file = file_get_contents($url , false , stream_context_create($arrContextOptions) );

        } catch (\Exception $e) {

            return ['status' => 'error', 'message' => '文件下载错误！' . $e->getMessage(), 'code' => '101'];
            //throw new \Exception ('文件下载错误！');
        }

        file_put_contents($path . $fileName, $file, LOCK_EX);

        return ['status' => 'success', 'message' => '下载完成!', 'data' => $path . $fileName, 'code' => 200];
    }

    /**
     * 移动文件 传绝对路径
     * @param file 原文件路径
     * @param newFile 新文件路径
     */
    public function moveFile($file = '', $newFile = '')
    {
        if (!file_exists($file)) {
            return ['status' => 'error', 'code' => '101', 'message' => '待移入文件不存在！'];
        }

        $pathinfo = pathinfo($newFile);

        if (!file_exists($pathinfo['dirname'])) {

            mkdir($pathinfo['dirname'], 0777, true);
        }

        copy($file, $newFile); //拷贝到新目录

        // unlink($file); //删除旧目录下的文件
    }

    /**
     * 复制目录
     */
    public function recurse_copy($src, $dst)
    {
        // 原目录，复制到的目录

        $dir = opendir($src);
        @mkdir($dst);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($src . '/' . $file)) {
                    $this->recurse_copy($src . '/' . $file, $dst . '/' . $file);
                } else {
                    copy($src . '/' . $file, $dst . '/' . $file);
                }
            }
        }
        closedir($dir);
    }

    /**
     * 删除指定文件夹以及文件夹下的所有文件
     */
    public function deldir($dir)
    {
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }

        closedir($dh);
        //删除当前文件夹：
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

}
